import 'package:flutter/material.dart';
import 'package:flutter_trip/dao/search_dao.dart';
import 'package:flutter_trip/widget/search_bar.dart';

import '../model/search_model.dart';
import '../widget/webview.dart';

const searchUrlConstants =
    "https://m.ctrip.com/restapi/h5api/globalsearch/search?source=mobileweb&action=mobileweb&keyword=";

class SearchPage extends StatefulWidget {
  final bool hideLeft;
  final String searchUrl;
  final String keyword;
  final String hint;

  const SearchPage(
      {super.key,
      this.hideLeft = false,
      this.searchUrl = searchUrlConstants,
      this.keyword = "",
      this.hint = ""});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  SearchModel? searchModel;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          _appBar,
          MediaQuery.removePadding(
            removeTop: true,
            context: context,
            child: Expanded(
              flex: 1,
              child: _listView,
            ),
          ),
        ],
      ),
    );
  }

  Widget get _appBar {
    return Column(
      children: [
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0x66000000), Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Container(
            padding: const EdgeInsets.only(top: 40),
            height: 80,
            decoration: const BoxDecoration(
              color: Colors.white,
            ),
            child: CustomSearchBar(
              hideLeft: widget.hideLeft,
              defaultText: widget.keyword,
              hint: widget.hint,
              leftButtonClick: () {
                Navigator.pop(context);
              },
              onChanged: _onTextChange,
            ),
          ),
        ),
      ],
    );
  }

  _onTextChange(String text) {
    if (text.isEmpty) {
      setState(() {
        searchModel = null;
      });
      return;
    }
    String url = widget.searchUrl + text;
    SearchDao.fetch(url, text).then((SearchModel model) {
      if (model.keyword == text) {
        setState(() {
          searchModel = model;
        });
      }
    }).catchError((e) {
      print(e);
    });
  }

  Widget get _listView {
    return ListView.builder(
      itemBuilder: (BuildContext context, int position) {
        return _item(position);
      },
      itemCount: searchModel?.data?.length ?? 0,
    );
  }

  _item(int position) {
    if (searchModel == null || searchModel?.data == null) {
      return null;
    }
    SearchItem item = searchModel!.data![position];
    return GestureDetector(
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return WebView(
            url: item.url!,
            title: '详情',
          );
        }));
      },
      child: Container(
        padding: const EdgeInsets.all(10),
        decoration: const BoxDecoration(
          border: Border(bottom: BorderSide(width: 0.3, color: Colors.grey)),
        ),
        child: Row(
          children: [
            Container(
              margin: const EdgeInsets.only(right: 10),
              child: item.imageUrl != null
                  ? Image.network(
                      item.imageUrl!,
                      height: 28,
                      width: 28,
                    )
                  : const Icon(
                      Icons.window,
                      size: 28,
                      color: Colors.blue,
                    ),
            ),
            Column(
              children: [
                SizedBox(
                  width: 300,
                  child: _title(item),
                ),
                Container(
                  width: 300,
                  margin: const EdgeInsets.only(top: 5),
                  child: _subTitle(item),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  _keywordTextSpans(String? word, String? keyword) {
    List<TextSpan> spans = [];
    if (word == null || word.isEmpty || keyword == null || keyword.isEmpty) {
      return spans;
    }
    List<String> keywordArr = word.split(keyword);
    TextStyle normalStyle =
        const TextStyle(fontSize: 16, color: Colors.black87);
    TextStyle keywordStyle =
        const TextStyle(fontSize: 16, color: Colors.orange);
    for (int i = 0; i < keywordArr.length; i++) {
      if ((i + 1) % 2 == 0) {
        spans.add(TextSpan(text: keyword, style: keywordStyle));
      }
      String val = keywordArr[i];
      if (val.isNotEmpty) {
        spans.add(TextSpan(text: val, style: normalStyle));
      }
    }
    return spans;
  }

  _title(SearchItem? item) {
    if (item == null) {
      return null;
    }
    List<TextSpan> spans = [];
    spans.addAll(_keywordTextSpans(item.word, searchModel?.keyword));
    spans.add(TextSpan(
      text: " ${item.districtname ?? ''} ${item.zonename ?? ''}",
      style: const TextStyle(
        fontSize: 16,
        color: Colors.grey,
      ),
    ));
    return RichText(text: TextSpan(children: spans));
  }

  _subTitle(SearchItem? item) {
    if (item == null) {
      return null;
    }
    return RichText(
        text: TextSpan(children: [
      TextSpan(
        text: item.price ?? '',
        style: const TextStyle(
          fontSize: 16,
          color: Colors.orange,
        ),
      ),
      TextSpan(
        text: " ${item.star ?? ''}",
        style: const TextStyle(
          fontSize: 12,
          color: Colors.grey,
        ),
      ),
    ]));
  }
}
